// pages/demo/demo.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */

  data: {
    APPID: "wx79e43413fd0e8b18",
    SECRET: "c5a0ff6a9165804b1026301c17c52444",

    hasLogin: false
  },

  relogin:function(){

    // wx.setStorage({
    //   key: 'hasLogin',
    //   data: false
    // })

    // wx.redirectTo({
    //   url:'../demo/demo'
    // })
  },

  shouquan: function () {
    // wx.setStorage({
    //   key: 'mm',
    //   data: 2,
    // })
    // console.log(wx.getStorageSync('mm'))

    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res.userInfo.nickName)
        app.nickName = res.userInfo.nickName
        app.avatarUrl = res.userInfo.avatarUrl
        app.gender = res.userInfo.gender
        app.hasUserInfo = true
        wx.login({
          success: (res) => {
            // console.log(res.code)
            if (res.code) {
              //发起网络请求
              wx.request({
                url: "https://api.weixin.qq.com/sns/jscode2session?appid=" + this.data.APPID + "&secret=" + this.data.SECRET + "&js_code=" + res.code + "&grant_type=authorization_code",
                success: (res2) => {
                  //查找数据库中是否有相同id  openid作id
                  console.log(res2.data)
                  wx.request({
                    url: 'http://120.24.97.106:8081/findUserById',
                    method: 'POST',
                    data: {
                      "userid": res2.data.openid,
                    },
                    success: (res3) => {
                      if (res3.data.length != 0) {
                        this.setData({
                          hasLogin:true
                        })
                        wx.setStorage({
                          key: 'hasLogin',
                          data: true
                        })
                        //数据库已经有，直接登录
                        wx.showLoading({
                          title: '登录中...',
                        })
                        setTimeout(function () {
                          wx.switchTab({
                            url: '../p1/p1',
                          });
                          wx.hideLoading()
                        }, 2000)
                        console.log("登录成功")
                        //用户数据赋值到全局变量
                        app.userid = res3.data[0].userid
                        app.nickName = res3.data[0].nickName
                        app.sex = res3.data[0].sex
                        app.avatarUrl = res3.data[0].avatarUrl
                        app.hasUserInfo = res3.data[0].hasUserInfo
                      } else {
                        wx.request({
                          url: 'http://120.24.97.106:8081/zhuceSaveUser',
                          method: 'POST',
                          data: {
                            "userid": res2.data.openid,
                          },
                          success: () => {
                            app.userid = res2.data.openid

                            console.log("用户openid注册成功")

                            //主页的数据第一次加载数据库
                            wx.request({
                              url: 'http://120.24.97.106:8081/theme/saveTheme',
                              method: 'POST',
                              data: {
                                "userid": res2.data.openid,
                                "pictureid": app.selectId,
                                "pictureUrl": app.pictureUrl,
                                "texts": app.p2_toptexts
                              },
                              success: () => {
                                console.log("载入主页数据成功")
                              }
                            });


                            wx.request({
                              url: 'http://120.24.97.106:8081/saveUserFromWx',
                              method: 'POST',
                              data: {
                                "userid": res2.data.openid,
                                "nickName": app.nickName,
                                "avatarUrl": app.avatarUrl,
                                "sex": app.gender,
                                "hasUserInfo": app.hasUserInfo
                              },
                              success: () => {
                                this.setData({
                                  hasLogin:true
                                })
                                wx.setStorage({
                                  key: 'hasLogin',
                                  data: true
                                })
                                console.log("保存微信数据成功")
                                wx.showLoading({
                                  title: '登录中...',
                                })
                                setTimeout(function () {
                                  wx.switchTab({
                                    url: '../p1/p1',
                                  });
                                  wx.hideLoading()
                                }, 2000)
                              }
                            })
                          }
                        })
                      }
                    }
                  })
                }

              })
            }
          }
        })
      },
      fail: (res) => {
        console.log("用户取消授权")
      }
    })


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var hasLogin = wx.getStorageSync('hasLogin')
    this.setData({
      hasLogin: hasLogin
    })
    wx.login({
      success: (res) => {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: "https://api.weixin.qq.com/sns/jscode2session?appid=" + this.data.APPID + "&secret=" + this.data.SECRET + "&js_code=" + res.code + "&grant_type=authorization_code",
            success: (res2) => {
              //查找数据库中是否有相同id  openid作id
              wx.request({
                url: 'http://120.24.97.106:8081/findUserById',
                method: 'POST',
                data: {
                  "userid": res2.data.openid,
                },
                success: (res3) => {
                  if (res3.data.length != 0) {
                    this.setData({
                      hasLogin: true
                    })
                    wx.setStorage({
                      key: 'hasLogin',
                      data: true
                    })
                    //数据库已经有，直接登录
                    wx.showLoading({
                      title: '登录中...',
                    })
                    setTimeout(function () {
                      wx.switchTab({
                        url: '../p1/p1',
                      });
                      wx.hideLoading()
                    }, 2000)
                    console.log("登录成功")
                    //用户数据赋值到全局变量
                    app.userid = res3.data[0].userid
                    app.nickName = res3.data[0].nickName
                    app.sex = res3.data[0].sex
                    app.avatarUrl = res3.data[0].avatarUrl
                    app.hasUserInfo = res3.data[0].hasUserInfo
                  } else {
                    this.setData({
                      hasLogin: false
                    })
                    wx.setStorage({
                      key: 'hasLogin',
                      data: false
                    })
                    console.log("登录失败")
                  }
                }
              })
            }

          })
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})